package com.steven.sync.mianshi;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 一个容器两个方法 add ,size,
 * 两个线程 一个线程add 10次 另外一个线程监听到大小等于5 的时候给出提示并结束
 */
public class Test1_CountDown {

     //volatile修饰引用类型改变了其他线程是看不到的，除非引用本身改了
    static volatile List list = Collections.synchronizedList(new ArrayList<>());


    public void add(Object o) {
        list.add(o);
    }

    public Integer size() {
        return list.size();
    }


    public static void main(String[] args) {
        Test1_CountDown test1  =new Test1_CountDown();
        CountDownLatch countDownLatch1 = new CountDownLatch(1);
        CountDownLatch countDownLatch2 = new CountDownLatch(1);

        new Thread(() -> {
                if (test1.size() != 5) {
                    try {
                        countDownLatch1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("size已经等于5");
                //继续运行第一个线程
                countDownLatch2.countDown();
        }).start();

        new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    test1.add(new Object());
                    if(test1.size() ==5){
                        try {
                            //启动第一个线程
                            countDownLatch1.countDown();
                            //当前线程阻塞
                            countDownLatch2.await();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
        }).start();



    }


}
